// Mock数据生成器 - 用于生成实盘页面所需的所有API模拟数据

// 随机工具函数（本地实现，避免缺失模块）
function randomFloat(min: number, max: number): number {
  return Math.random() * (max - min) + min;
}

function randomInt(min: number, max: number): number {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randomString(length: number): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

function randomDate(start: Date, end: Date): Date {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

// 主要模型列表
export const MODELS = [
  { id: 'qwen3-max', name: 'Qwen3 Max', displayName: 'QWEN3 MAX' },
  { id: 'deepseek-chat-v3.1', name: 'DeepSeek Chat V3.1', displayName: 'DEEPSEEK CHAT V3.1' },
  { id: 'claude-sonnet-4-5', name: 'Claude Sonnet 4.5', displayName: 'CLAUDE SONNET 4.5' },
  { id: 'grok-4', name: 'Grok 4', displayName: 'GROK 4' },
  { id: 'gemini-2.5-pro', name: 'Gemini 2.5 Pro', displayName: 'GEMINI 2.5 PRO' },
  { id: 'gpt-5', name: 'GPT-5', displayName: 'GPT-5' }
];

// 加密货币列表
export const CRYPTO_SYMBOLS = ['BTC', 'ETH', 'SOL', 'BNB', 'DOGE', 'XRP'];

// 基础价格（用于生成合理的价格波动）
const BASE_PRICES = {
  BTC: 70000,
  ETH: 3500,
  SOL: 120,
  BNB: 500,
  DOGE: 0.15,
  XRP: 0.6
};

/**
 * 生成加密货币价格模拟数据
 */
export function generateCryptoPrices() {
  const prices: Record<string, { symbol: string; price: number; timestamp: number }> = {};
  
  CRYPTO_SYMBOLS.forEach(symbol => {
    const basePrice = BASE_PRICES[symbol as keyof typeof BASE_PRICES];
    // 生成±2%的价格波动
    const priceChange = (Math.random() - 0.5) * 0.04 * basePrice;
    const finalPrice = basePrice + priceChange;
    
    prices[symbol] = {
      symbol,
      price: Number(finalPrice.toFixed(symbol === 'DOGE' ? 4 : 2)),
      timestamp: Date.now()
    };
  });
  
  return {
    prices,
    serverTime: Date.now()
  };
}

/**
 * 生成账户总值模拟数据
 */
export function generateAccountTotals(lastHourlyMarker?: number) {
  const accountTotals = MODELS.map(model => {
    // 基础账户价值（不同模型有不同的基础值）
    const baseValue = 100000 + MODELS.indexOf(model) * 10000;
    // 随机生成收益率（-5%到15%之间）
    const returnRate = (Math.random() * 0.2) - 0.05;
    const accountValue = baseValue * (1 + returnRate);
    
    // 随机生成一些未实现和已实现盈亏
    const unrealizedPnl = accountValue * (Math.random() * 0.06 - 0.02);
    const realizedPnl = accountValue * (Math.random() * 0.08 - 0.01);
    
    return {
      model_id: model.id,
      timestamp: Math.floor(Date.now() / 1000),
      account_value: Number(accountValue.toFixed(2)),
      dollar_equity: Number(accountValue.toFixed(2)),
      realized_pnl: Number(realizedPnl.toFixed(2)),
      unrealized_pnl: Number(unrealizedPnl.toFixed(2)),
      return_pct: Number((returnRate * 100).toFixed(2)),
      since_inception_hourly_marker: lastHourlyMarker ? lastHourlyMarker + 1 : Math.floor(Date.now() / 3600000),
      hourly_marker: Math.floor(Date.now() / 3600000)
    };
  });
  
  return { accountTotals };
}

/**
 * 生成持仓信息模拟数据
 */
export function generatePositions(limit = 1000) {
  const positions: any[] = [];
  
  // 为每个模型生成一些持仓
  MODELS.forEach(model => {
    // 每个模型1-5个持仓
    const positionCount = randomInt(1, 5);
    
    for (let i = 0; i < positionCount && positions.length < limit; i++) {
      const symbol = CRYPTO_SYMBOLS[randomInt(0, CRYPTO_SYMBOLS.length - 1)];
      const basePrice = BASE_PRICES[symbol as keyof typeof BASE_PRICES];
      const entryPrice = basePrice * (1 + (Math.random() * 0.1 - 0.05));
      const currentPrice = entryPrice * (1 + (Math.random() * 0.15 - 0.07));
      
      // 随机决定多空
      const isLong = Math.random() > 0.4;
      const quantity = randomFloat(0.1, 10) * (isLong ? 1 : -1);
      const leverage = randomInt(1, 5);
      const margin = Math.abs(quantity) * entryPrice / leverage;
      const unrealizedPnl = Math.abs(quantity) * (currentPrice - entryPrice) * (isLong ? 1 : -1);
      
      positions.push({
        model_id: model.id,
        entry_oid: randomInt(100000, 999999),
        risk_usd: margin * 0.1,
        confidence: Number((Math.random() * 0.4 + 0.6).toFixed(2)), // 0.6-1.0
        exit_plan: {
          profit_target: entryPrice * (1 + (Math.random() * 0.1 + 0.05)),
          stop_loss: entryPrice * (1 - (Math.random() * 0.05 + 0.02)),
          invalidation_condition: `Price goes below ${Number(entryPrice * 0.98).toFixed(2)}`
        },
        entry_time: Math.floor((Date.now() - randomInt(1000 * 60 * 60, 1000 * 60 * 60 * 24)) / 1000),
        symbol,
        entry_price: Number(entryPrice.toFixed(symbol === 'DOGE' ? 4 : 2)),
        margin: Number(margin.toFixed(2)),
        leverage,
        quantity: Number(quantity.toFixed(symbol === 'DOGE' ? 0 : 4)),
        current_price: Number(currentPrice.toFixed(symbol === 'DOGE' ? 4 : 2)),
        unrealized_pnl: Number(unrealizedPnl.toFixed(2))
      });
    }
  });
  
  return positions;
}

/**
 * 生成交易历史模拟数据
 */
export function generateTrades(count = 30) {
  const trades = [];
  const now = Math.floor(Date.now() / 1000);
  
  for (let i = 0; i < count; i++) {
    const model = MODELS[randomInt(0, MODELS.length - 1)];
    const symbol = CRYPTO_SYMBOLS[randomInt(0, CRYPTO_SYMBOLS.length - 1)];
    const basePrice = BASE_PRICES[symbol as keyof typeof BASE_PRICES];
    
    // 生成过去30天内的随机交易时间
    const entryTime = now - randomInt(86400, 86400 * 30);
    // 交易持续时间（1小时到2天）
    const duration = randomInt(3600, 43200);
    const exitTime = entryTime + duration;
    
    // 生成入场价格和出场价格
    const entryPrice = basePrice * (1 + (Math.random() * 0.1 - 0.05));
    const profitRate = (Math.random() * 0.16 - 0.04); // -4%到12%的收益
    const exitPrice = entryPrice * (1 + profitRate);
    
    // 交易方向
    const side = Math.random() > 0.4 ? 'long' : 'short';
    const quantity = randomFloat(0.1, 5);
    const leverage = randomInt(1, 5);
    
    // 计算盈亏
    const realizedGrossPnl = quantity * (exitPrice - entryPrice) * (side === 'long' ? 1 : -1);
    const commission = Math.abs(realizedGrossPnl) * 0.001; // 0.1%手续费
    const realizedNetPnl = realizedGrossPnl - commission;
    
    trades.push({
      id: `trade_${randomString(10)}`,
      symbol,
      model_id: model.id,
      side,
      entry_price: Number(entryPrice.toFixed(symbol === 'DOGE' ? 4 : 2)),
      exit_price: Number(exitPrice.toFixed(symbol === 'DOGE' ? 4 : 2)),
      quantity: Number(quantity.toFixed(symbol === 'DOGE' ? 0 : 4)),
      leverage,
      entry_time: entryTime,
      exit_time: exitTime,
      realized_net_pnl: Number(realizedNetPnl.toFixed(2)),
      realized_gross_pnl: Number(realizedGrossPnl.toFixed(2)),
      total_commission_dollars: Number(commission.toFixed(2))
    });
  }
  
  // 按出场时间排序，最新的在前
  trades.sort((a, b) => b.exit_time - a.exit_time);
  
  return trades;
}

/**
 * 生成账户价值历史数据
 */
export function generateSinceInceptionValues() {
  const now = Date.now();
  const days = 90; // 生成90天的数据
  const data: Record<string, any[]> = {};
  
  MODELS.forEach(model => {
    const modelData = [];
    let value = 100000 + MODELS.indexOf(model) * 10000; // 初始账户价值
    
    for (let i = days; i >= 0; i--) {
      const timestamp = now - (i * 24 * 60 * 60 * 1000);
      // 每天随机波动±1%
      value = value * (1 + (Math.random() * 0.02 - 0.01));
      
      modelData.push({
        timestamp: Math.floor(timestamp / 1000),
        value: Number(value.toFixed(2))
      });
    }
    
    data[model.id] = modelData;
  });
  
  return data;
}

/**
 * 生成对话历史模拟数据
 */
export function generateConversations() {
  const conversations = MODELS.map(model => {
    const messages = [];
    const messageCount = randomInt(3, 8);
    
    // 生成系统消息
    messages.push({
      role: 'system',
      content: 'You are a professional cryptocurrency trading assistant. Analyze market data and make trading decisions.',
      timestamp: Math.floor((Date.now() - randomInt(1000 * 60 * 30, 1000 * 60 * 60 * 24)) / 1000)
    });
    
    // 生成一些用户和助手消息
    for (let i = 0; i < messageCount; i++) {
      const isAssistant = i % 2 === 0;
      const symbols = CRYPTO_SYMBOLS.slice(0, randomInt(2, 4));
      
      let content = '';
      if (isAssistant) {
        const action = ['建议买入', '建议卖出', '保持观望', '建议减仓', '建议加仓'][randomInt(0, 4)];
        const reason = ['技术指标看涨', '基本面强劲', '市场情绪积极', '均线金叉', '交易量增加'][randomInt(0, 4)];
        content = `${action} ${symbols.join('、')}。${reason}，预计短期内有${Number((Math.random() * 5 + 2).toFixed(1))}%的上涨空间。`;
      } else {
        content = `请分析${symbols.join('、')}的最新走势，有什么交易机会？`;
      }
      
      messages.push({
        role: isAssistant ? 'assistant' : 'user',
        content,
        timestamp: Math.floor((Date.now() - randomInt(1000 * 60 * 10, 1000 * 60 * 60)) / 1000)
      });
    }
    
    return {
      model_id: model.id,
      messages: messages.sort((a, b) => a.timestamp - b.timestamp)
    };
  });
  
  return conversations;
}

/**
 * 生成排行榜模拟数据
 */
export function generateLeaderboard() {
  return MODELS.map(model => {
    // 生成随机性能数据
    const accountValue = 100000 + randomFloat(-20000, 50000);
    const returnPct = (Math.random() * 30 - 10); // -10%到20%
    const totalPnl = accountValue * 0.1 * (Math.random() * 2 - 0.5);
    const fees = Math.abs(totalPnl) * 0.02;
    const winRate = Math.random() * 0.4 + 0.4; // 40%到80%
    const biggestWin = totalPnl * 0.5 * (Math.random() + 1);
    const biggestLoss = -Math.abs(totalPnl) * 0.3 * (Math.random() + 1);
    const sharpeRatio = Math.random() * 2 + 0.5;
    const tradesCount = randomInt(50, 200);
    
    return {
      model_id: model.id,
      model_name: model.name,
      account_value: Number(accountValue.toFixed(2)),
      return_pct: Number(returnPct.toFixed(2)),
      total_pnl: Number(totalPnl.toFixed(2)),
      fees: Number(fees.toFixed(2)),
      win_rate: Number((winRate * 100).toFixed(2)),
      biggest_win: Number(biggestWin.toFixed(2)),
      biggest_loss: Number(biggestLoss.toFixed(2)),
      sharpe_ratio: Number(sharpeRatio.toFixed(2)),
      trades_count: tradesCount
    };
  }).sort((a, b) => b.return_pct - a.return_pct); // 按收益率排序
}

/**
 * 生成分析数据模拟数据
 */
export function generateAnalytics() {
  return MODELS.map(model => {
    const averageTradeSize = randomFloat(1000, 5000);
    const medianTradeSize = randomFloat(800, 4000);
    const averageHoldTime = randomInt(2, 24); // 小时
    const medianHoldTime = randomInt(1, 12); // 小时
    const pctLong = Math.random() * 60 + 30; // 30%到90%
    const expectancy = randomFloat(-0.05, 0.15);
    const medianLeverage = randomFloat(1, 3);
    const averageLeverage = randomFloat(1, 4);
    const averageConfidence = randomFloat(0.6, 0.95);
    const medianConfidence = randomFloat(0.65, 0.9);
    
    return {
      model_id: model.id,
      average_trade_size: Number(averageTradeSize.toFixed(2)),
      median_trade_size: Number(medianTradeSize.toFixed(2)),
      average_hold_time: averageHoldTime,
      median_hold_time: medianHoldTime,
      pct_long: Number(pctLong.toFixed(2)),
      expectancy: Number(expectancy.toFixed(4)),
      median_leverage: Number(medianLeverage.toFixed(2)),
      average_leverage: Number(averageLeverage.toFixed(2)),
      average_confidence: Number(averageConfidence.toFixed(2)),
      median_confidence: Number(medianConfidence.toFixed(2))
    };
  });
}

/**
 * 生成单个模型详细分析数据
 */
export function generateModelAnalytics(modelId: string) {
  const model = MODELS.find(m => m.id === modelId) || MODELS[0];
  
  return {
    model_id: model.id,
    model_name: model.name,
    display_name: model.displayName,
    // 基础统计
    account_value: Number((100000 + randomFloat(-10000, 30000)).toFixed(2)),
    return_pct: Number((Math.random() * 25 - 5).toFixed(2)),
    total_trades: randomInt(50, 150),
    win_rate: Number((Math.random() * 30 + 50).toFixed(2)),
    
    // 高级统计
    average_trade_size: Number(randomFloat(1000, 3000).toFixed(2)),
    average_hold_time: randomInt(1, 12),
    average_leverage: Number(randomFloat(1, 3).toFixed(2)),
    average_confidence: Number(randomFloat(0.6, 0.9).toFixed(2)),
    
    // 持仓信息
    active_positions: generatePositions().filter(p => p.model_id === modelId),
    
    // 最近交易
    recent_trades: generateTrades(10).filter(t => t.model_id === modelId),
    
    // 月度表现
    monthly_performance: [
      { month: 'Jan', return_pct: Number((Math.random() * 10 - 3).toFixed(2)) },
      { month: 'Feb', return_pct: Number((Math.random() * 10 - 3).toFixed(2)) },
      { month: 'Mar', return_pct: Number((Math.random() * 10 - 3).toFixed(2)) },
      { month: 'Apr', return_pct: Number((Math.random() * 10 - 3).toFixed(2)) },
      { month: 'May', return_pct: Number((Math.random() * 10 - 3).toFixed(2)) },
      { month: 'Jun', return_pct: Number((Math.random() * 10 - 3).toFixed(2)) },
    ],
    
    // 资产配置
    asset_allocation: CRYPTO_SYMBOLS.map(symbol => ({
      symbol,
      allocation_pct: Number((Math.random() * 40).toFixed(2))
    })).sort((a, b) => b.allocation_pct - a.allocation_pct)
  };
}

/**
 * 随机工具函数
 */